<template>
  <div class="min-h-screen bg-gradient-to-b from-blue-50 to-white">
    <main class="max-w-4xl mx-auto px-4 py-8 sm:py-12">
      <!-- 搜索标题 -->
      <div class="text-center mb-8 sm:mb-12">
        <h2 class="text-2xl sm:text-3xl font-bold text-gray-800 mb-2 sm:mb-3 hover:text-blue-600 transition-colors">
          语义文献检索
        </h2>
        <p class="text-sm sm:text-base text-gray-600">输入问题或描述，找到相关研究文献</p>
      </div>

      <!-- 搜索框区域 -->
      <div class="relative mb-6 sm:mb-8 bg-white rounded-xl shadow-lg p-4 sm:p-8 max-w-6xl mx-auto">
        <textarea
          v-model="searchQuery"
          placeholder="请输入您的研究问题或描述..."
          class="w-full px-4 sm:px-8 py-4 sm:py-6 text-base sm:text-lg border rounded-lg shadow-sm
                 focus:ring-2 focus:ring-blue-400 focus:border-blue-400
                 transition duration-200 min-h-[150px] sm:min-h-[200px] resize-none"
          @keyup.ctrl.enter="handleSearch"
        ></textarea>
        
        <!-- 按钮组 -->
        <div class="flex flex-col gap-3 sm:gap-4 mt-4 sm:mt-6">
          <button 
            v-if="searchQuery.trim()"
            @click="enhanceQuery"
            class="w-full bg-green-600 text-white px-4 sm:px-8 py-3 sm:py-4 rounded-lg
                   hover:bg-green-700 transition duration-200 flex items-center justify-center
                   text-sm sm:text-base"
            :disabled="isEnhancing"
          >
            <i class="fas fa-magic mr-2"></i>
            {{ isEnhancing ? '增强中...' : '问题增强' }}
          </button>
          
          <button 
            @click="handleSearch"
            class="w-full bg-blue-600 text-white px-4 sm:px-8 py-3 sm:py-4 rounded-lg
                   hover:bg-blue-700 transition duration-200 flex items-center justify-center
                   text-sm sm:text-base"
          >
            <i class="fas fa-search mr-2"></i>
            开始搜索
          </button>
        </div>
      </div>

      <!-- 搜索提示 -->
      <div class="text-center text-gray-600 text-xs sm:text-sm bg-white p-3 sm:p-4 rounded-lg shadow-sm">
        <p>提示：输入完整的问题或研究描述可以获得更好的搜索结果</p>
        <p class="mt-2">按 Ctrl + Enter 快捷搜索</p>
      </div>

      <!-- 禁用的功能提示 -->
      <div class="mt-6 sm:mt-8 p-3 sm:p-4 bg-gray-100 rounded-lg">
        <p class="text-gray-500 text-center text-xs sm:text-sm">
          高级筛选功能正在开发中...
        </p>
      </div>

      <!-- 进度弹窗 -->
      <Transition name="fade">
        <div v-if="isSearching" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div class="bg-white rounded-xl p-8 max-w-4xl w-full mx-6 min-h-[400px]">
            <h3 class="text-2xl font-bold text-blue-700 mb-6">分析进度</h3>
            <ul class="space-y-4">
              <li v-for="(step, index) in thinkingSteps" 
                  :key="index" 
                  class="flex items-center text-lg"
                  :class="index <= currentStep ? 'text-blue-600' : 'text-gray-400'">
                <span class="mr-3 text-xl" :class="index <= currentStep ? 'text-blue-600' : 'text-gray-400'">
                  {{ index <= currentStep ? '✓' : '○' }}
                </span>
                {{ step }}
              </li>
            </ul>
          </div>
        </div>
      </Transition>
    </main>
  </div>


  <!-- 检索结果页面 -->
  <Transition name="fade">
    <div v-if="isResultDialogOpen" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" @click="isResultDialogOpen = false">
      <div class="bg-white rounded-xl p-4 sm:p-8 w-11/12 max-w-6xl mx-auto max-h-[95vh] overflow-y-auto relative" @click.stop>
        <!-- 关闭按钮 -->
        <button 
          @click="isResultDialogOpen = false"
          class="absolute top-4 right-4 text-blue-400 hover:text-blue-600 transition-colors p-2 rounded-full hover:bg-blue-100"
        >
          <i class="fas fa-times text-lg sm:text-xl">关闭</i>
          <span class="sr-only">关闭</span>
        </button>

        <!-- 标题 -->
        <h3 class="text-xl sm:text-2xl font-bold text-blue-700 text-center mb-4 sm:mb-6 mt-2">文献检索结果</h3>

        <div v-if="searchResults" class="space-y-6 sm:space-y-8">
          <!-- 分析报告 -->
          <div class="bg-white rounded-xl shadow-lg p-4 sm:p-8">
            <h4 class="font-semibold text-gray-800 text-lg sm:text-xl mb-3 sm:mb-4">分析报告</h4>
            <div class="prose max-w-none text-sm sm:text-base" 
                 v-html="processReport(searchResults.report)">
            </div>
          </div>

          <!-- 文献列表 -->
          <div class="space-y-4 sm:space-y-6">
            <div v-for="(result, index) in searchResults.results" 
                 :key="index"
                 :id="'paper-' + index"
                 class="bg-white rounded-xl shadow-lg p-4 sm:p-8 transition-all hover:shadow-xl">
              <div class="flex items-start justify-between">
                <div class="flex-1">
                  <div class="inline-flex items-center justify-center bg-blue-100 text-blue-600 rounded-full w-6 h-6 sm:w-7 sm:h-7 text-xs sm:text-sm font-medium">
                    {{ index + 1 }}
                  </div>
                  <h5 class="text-lg sm:text-2xl font-medium text-blue-600 mt-2">{{ result.title }}</h5>
                  <p class="text-sm sm:text-base text-gray-500 mt-2 sm:mt-3">
                    <i class="fas fa-users mr-2"></i>{{ result.authors }}
                    <span class="mx-3">|</span>
                    <i class="far fa-calendar-alt mr-2"></i>{{ result.date }}
                    <span class="mx-3">|</span>
                    <i class="fas fa-book mr-2"></i>{{ result.journal }}
                  </p>
                </div>
                <a :href="result.url" 
                   target="_blank" 
                   class="ml-4 sm:ml-6 px-4 sm:px-6 py-2 sm:py-3 bg-blue-50 text-blue-600 rounded-lg hover:bg-blue-100 transition-colors text-sm sm:text-base"
                >
                  <i class="fas fa-external-link-alt mr-2"></i>原文
                </a>
              </div>
              <p class="text-gray-600 mt-4 sm:mt-6 leading-relaxed text-sm sm:text-lg">{{ result.abstract }}</p>
            </div>
          </div>
        </div>

        <div v-else class="text-center text-gray-500 py-12 sm:py-16">
          <i class="fas fa-search text-4xl sm:text-6xl mb-4 sm:mb-6"></i>
          <p class="text-lg sm:text-xl">暂无检索结果</p>
        </div>
      </div>
    </div>
  </Transition>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'

const md = new MarkdownIt()


const searchQuery = ref<string>('')
const isEnhancing = ref<boolean>(false)
const isSearching = ref<boolean>(false)
const searchError = ref<string>('')
const currentStep = ref<number>(0)
const isResultDialogOpen = ref<boolean>(false)
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)

const searchResults = ref<{
  report: string,
  results: {
    title: string,
    abstract: string,
    authors: string,
    date: string,
    url: string,
    journal: string
  }[]
}>({
  report: '分析报告',
  results: [{
    title: '标题',
    abstract: '摘要',
    authors: '作者',
    date: '日期',
    url: '链接',
    journal: '期刊'
  }]
})

const totalPages = computed(() => Math.ceil(searchResults.value.results.length / pageSize.value))

const displayedPages = computed(() => {
  const pages: (number | string)[] = []
  const maxVisiblePages = 5
  
  if (totalPages.value <= maxVisiblePages) {
    for (let i = 1; i <= totalPages.value; i++) {
      pages.push(i)
    }
  } else {
    pages.push(1)
    if (currentPage.value > 3) {
      pages.push('...')
    }
    
    for (let i = Math.max(2, currentPage.value - 1); 
         i <= Math.min(totalPages.value - 1, currentPage.value + 1); 
         i++) {
      pages.push(i)
    }
    
    if (currentPage.value < totalPages.value - 2) {
      pages.push('...')
    }
    pages.push(totalPages.value)
  }
  
  return pages
})

const paginatedResults = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return searchResults.value.results.slice(start, end)
})

const thinkingSteps = ref<string[]>([
  '分析查询意图...',
  '生成检索词...',
  '执行文献检索...',
  '计算相关性得分...',
  '结果排序与筛选...',
  '生成摘要与推荐...'
])

const enhanceQuery = async () => {
  if (!searchQuery.value.trim() || isEnhancing.value) return
  
  try {
    isEnhancing.value = true
    const response = await axios.post('/api/problem_enhancement', {
      user_input: searchQuery.value
    })
    searchQuery.value = response.data.searchQuery
  } catch (error) {
    console.error('问题增强失败:', error)
  } finally {
    isEnhancing.value = false
  }
}

const handleSearch = async () => {
  if (!searchQuery.value.trim()) return
  
  try {
    isSearching.value = true
    currentStep.value = 0
    searchError.value = ''
    currentPage.value = 1
    
    console.log('Search initiated with query:', searchQuery.value)
    
    const eventSource = new EventSource(`/api/search?query=${encodeURIComponent(searchQuery.value)}`, {
      withCredentials: true
    })
    
    let lastEventTime = Date.now()
    const heartbeatCheck = setInterval(() => {
      if (Date.now() - lastEventTime > 1000000000) { 
        console.log('Connection timeout')
        clearInterval(heartbeatCheck)
        eventSource.close()
        isSearching.value = false
        searchError.value = '搜索请求超时，请重试'
      }
    }, 5000)
    
    eventSource.onmessage = (event) => {
      lastEventTime = Date.now()
      console.log('Received SSE message:', event.data)
      
      try {
        const data = JSON.parse(event.data)
        console.log('Parsed data:', data)
        
        if (data.step !== undefined) {
          console.log('Updating step:', data.step)
          currentStep.value = data.step
          if (data.message) {
            console.log('Updating step message:', data.message)
            thinkingSteps.value[data.step] = data.message
          }
        }
        
        if (data.done && data.results) {
          clearInterval(heartbeatCheck)
          searchResults.value = {
            report: data.results.report || '暂无报告',
            results: data.results.results || []
          }
          isResultDialogOpen.value = true
          eventSource.close()
          isSearching.value = false
        }
      } catch (error) {
        console.error('Message processing error:', error, 'Raw data:', event.data)
      }
    }

    eventSource.onerror = (error) => {
      console.error('EventSource error:', error, 'ReadyState:', eventSource.readyState)
      searchError.value = '搜索请求失败，请重试'
      isSearching.value = false
      clearInterval(heartbeatCheck)
      eventSource.close()
    }
    
  } catch (error) {
    console.error('搜索初始化失败:', error)
    searchError.value = '无法启动搜索，请重试'
    isSearching.value = false
  }
}

// 添加处理报告的函数
const processReport = (report: string) => {
  // 处理带括号的多个数字引用
  let processedReport = report.replace(
    /\[(\d+(?:,\s*\d+)*)\]/g,
    (match, numbers) => {
      const nums = numbers.split(',').map(n => n.trim());
      return '[' + nums.map(num => {
        const index = parseInt(num) - 1;
        if (index >= 0 && index < searchResults.value.results.length) {
          return `<a href="#paper-${index}" class="citation-link">${num}</a>`;
        }
        return num;
      }).join(', ') + ']';
    }
  );
  
  // 处理末尾缺失方括号的数字引用
  processedReport = processedReport.replace(/\[(\d+)\s*(?![\]\)])/g, (match, num) => {
    const index = parseInt(num) - 1;
    if (index >= 0 && index < searchResults.value.results.length) {
      return `[<a href="#paper-${index}" class="citation-link">${num}</a>]`;
    }
    return `[${num}]`;
  });

  const mdOptions = {
    html: true,
    linkify: true,
    breaks: true
  };
  const md = new MarkdownIt(mdOptions);
  
  return md.render(processedReport);
}
</script>

<style scoped>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 添加 prose 样式覆盖 */
.prose :deep(p) {
  margin-top: 1em;
  margin-bottom: 1em;
}

.prose :deep(ul) {
  list-style-type: disc;
  padding-left: 1.5em;
}

.prose :deep(ol) {
  list-style-type: decimal;
  padding-left: 1.5em;
}

.prose :deep(h1),
.prose :deep(h2),
.prose :deep(h3),
.prose :deep(h4) {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
}

.prose :deep(blockquote) {
  border-left: 4px solid #3B82F6; /* 使用 Tailwind 的 blue-500 */
  padding: 1rem 1.5rem;
  margin: 1.5em 0;
  background-color: #EFF6FF; /* Tailwind 的 blue-50 */
  border-radius: 0.5rem;
  color: #1E40AF; /* Tailwind 的 blue-800 */
  font-style: italic;
}

.prose :deep(blockquote p) {
  margin: 0;
  line-height: 1.6;
}

.prose :deep(blockquote p:first-of-type::before) {
  content: '"';
  margin-right: 0.2em;
}

.prose :deep(blockquote p:last-of-type::after) {
  content: '"';
  margin-left: 0.2em;
}

/* 添加引用链接样式 */
:deep(.citation-link) {
  color: #2563EB; /* Tailwind blue-600 */
  text-decoration: none;
  padding: 0.1em 0.3em;
  border-radius: 0.25rem;
  background-color: #EFF6FF; /* Tailwind blue-50 */
  transition: all 0.2s ease;
}

:deep(.citation-link:hover) {
  background-color: #DBEAFE; /* Tailwind blue-100 */
  color: #1D4ED8; /* Tailwind blue-700 */
}

/* 确保方括号样式一致 */
:deep(.citation-link)::before,
:deep(.citation-link)::after {
  color: #6B7280; /* Tailwind gray-500 */
}
</style>